package cn.tedu.luban.worker.main.service;

import cn.tedu.luban.account.api.AccountApi;
import cn.tedu.luban.account.protocol.dto.AccountDTO;
import cn.tedu.luban.attach.api.AttachApi;
import cn.tedu.luban.attach.protocol.param.AttachUpdateParam;
import cn.tedu.luban.passport.protocol.jwt.UserPrinciple;
import cn.tedu.luban.passport.sdk.security.LubanSecurityContext;
import cn.tedu.luban.worker.main.converter.WorkerConverter;
import cn.tedu.luban.worker.main.repository.WorkerAreaRepository;
import cn.tedu.luban.worker.main.repository.WorkerCategoryRepository;
import cn.tedu.luban.worker.main.repository.WorkerRepository;
import cn.tedu.luban.worker.common.enums.WorkerResultEnum;
import cn.tedu.luban.worker.protocol.bo.FrontAccountBO;
import cn.tedu.luban.worker.protocol.bo.FrontWorkerBO;
import cn.tedu.luban.worker.protocol.bo.WorkerAreaBO;
import cn.tedu.luban.worker.protocol.bo.WorkerCategoryBO;
import cn.tedu.luban.worker.protocol.param.IdCardParam;
import cn.tedu.luban.worker.protocol.param.WorkerRegistParam;
import com.tedu.inn.commons.utils.Asserts;
import com.tedu.inn.protocol.exception.BusinessException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

@Service
@Slf4j
public class WorkerFrontService {
    /*@Autowired
    public WorkerFrontService(WorkerRepository workerRepository, WorkerAreaRepository workerAreaRepository,
        WorkerCategoryRepository workerCategoryRepository, AttachApi attachApi, WorkerConverter workerConverter,
        AccountApi accountApi) {
        this.workerRepository = workerRepository;
        this.workerAreaRepository = workerAreaRepository;
        this.workerCategoryRepository = workerCategoryRepository;
        this.attachApi = attachApi;
        this.workerConverter = workerConverter;
        this.accountApi = accountApi;
    }*/

    private static final Integer BUSINESS_TYPE=100;
    @Autowired
    private WorkerRepository workerRepository;
    @Autowired
    private WorkerAreaRepository workerAreaRepository;
    @Autowired
    private WorkerCategoryRepository workerCategoryRepository;
    @Autowired(required = false)
    private AttachApi attachApi;
    @Autowired
    private WorkerConverter workerConverter;
    @Autowired
    private AccountApi accountApi;
    @Transactional(rollbackFor = Exception.class)
    public Long createWorker(WorkerRegistParam workerParam) throws BusinessException {
        //补充userId
        Long userId=getUserId();
        workerParam.setUserId(userId);
        checkParam(workerParam);
        Long workerId=saveWorker(workerParam);
        saveAreas(workerParam);
        saveCategories(workerParam);
        return workerId;
    }
    private void saveCategories(WorkerRegistParam param) {
        workerCategoryRepository.delete(param.getUserId());
        workerCategoryRepository.saveWorkerCategories(param);
    }
    private void saveAreas(WorkerRegistParam param) {
        workerAreaRepository.delete(param.getUserId());
        workerAreaRepository.saveWorkerAreas(param);
    }
    private Long saveWorker(WorkerRegistParam param) throws BusinessException {
        //幂等性 删除worker
        workerRepository.delete(param.getUserId());
        //新增worker
        Long workerId=workerRepository.saveWorker(param);
        //远程调用绑定图片
        batchAttaches(param,BUSINESS_TYPE,workerId.intValue());
        return workerId;
    }
    private void batchAttaches(WorkerRegistParam param,Integer bizType, Integer bizId) throws BusinessException {
        List<IdCardParam> idCardParams = param.getAttachList();
        Asserts.isTrue(CollectionUtils.isEmpty(idCardParams),new BusinessException(WorkerResultEnum.ATTACH_ARGS_ERROR));
        List<AttachUpdateParam> attachUpdateParams = workerConverter.assembleAttachParam(idCardParams, bizType, bizId);
        try {
            int result = attachApi.batchUpdateAttachByIdList(attachUpdateParams);
            log.info("远程调用attachApi成功,返回结果为:{}",attachUpdateParams,result);
        }catch (Exception e) {
            log.error("远程调用attachApi失败,参数为:{},message:{}",attachUpdateParams,e.getMessage(),e);
            throw new BusinessException(WorkerResultEnum.ATTACH_UPDATE_FAILED);
        }
    }

    private void checkParam(WorkerRegistParam param) {
        //TODO
    }

    private Long getUserId() throws BusinessException {
        UserPrinciple token = LubanSecurityContext.getLoginToken();
        if (token==null){
            throw new BusinessException(WorkerResultEnum.USER_TOKEN_VERIFY_FAILED);
        }
        return token.getId();
    }

    public FrontWorkerBO detailWorker() throws BusinessException {
        Long userId=getUserId();
        FrontWorkerBO frontWorkerBO =workerRepository.getFrontWorker(userId);
        /*FrontAccountBO frontAccountBO =new FrontAccountBO();
        frontAccountBO.setTotalAmount(99999l);*/
        FrontAccountBO frontAccountBO=new FrontAccountBO();
        frontAccountBO.setTotalAmount(0L);
        if (frontWorkerBO ==null || frontWorkerBO.getId()==null){
            frontWorkerBO.setAuditStatus(3);
        }else {
            //查询worker的区域
            List<WorkerAreaBO> areaFrontBOS = workerAreaRepository.getFrontAreas(userId);
            frontWorkerBO.setWorkerAreaBOList(areaFrontBOS);
            //查询worker的分类
            List<WorkerCategoryBO> categoryFrontBOS = workerCategoryRepository.getFrontCategories(userId);
            frontWorkerBO.setWorkerCategoryBOList(categoryFrontBOS);
            AccountDTO account = accountApi.getAccount(frontWorkerBO.getUserId());
            if (account!=null && account.getTotalAmount()!=null) {
                frontAccountBO.setTotalAmount(account.getTotalAmount());
            }
        }
        frontWorkerBO.setFrontAccountBO(frontAccountBO);
        return frontWorkerBO;
    }
}
